/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rengwuxian.materialedittext;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.render.Arc;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import ohos.global.resource.*;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.OptionalInt;

/**
 * get resource class
 */
public class ResUtil {
    private static final String TAG = ResUtil.class.getSimpleName();

    private static final String CITY_ID_ATTR = "cityId_";

    private static final String STRING_ID_ATTR = "String_";

    private ResUtil() {}

    /**
     * get the path from id
     *
     * @param context the context
     * @param id      the id
     * @return the path from id
     */
    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException | NotExistException | WrongTypeException e) {
            path = "";
        }
        return path;
    }

    /**
     * get the new color
     *
     * @param context the context
     * @param id      the id
     * @return the color
     */
    public static Color getNewColor(Context context, int id) {
        return new Color(getColor(context, id));
    }

    /**
     * get the color
     *
     * @param context the context
     * @param id      the id
     * @return the color
     */
    public static int getColor(Context context, int id) {
        int result = 0;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getColor();
        } catch (IOException | WrongTypeException | NotExistException e) {
            result = 0;
        }
        return result;
    }

    /**
     * get the int
     *
     * @param context the context
     * @param id the int array
     * @return the int array
     */
    public static int getInt(Context context, int id) {
        int result = 0;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getInteger();
        } catch (IOException e) {
            result = 0;
        } catch (NotExistException e) {
            result = 0;
        } catch (WrongTypeException e) {
            result = 0;
        }
        return result;
    }
    /**
     * get the int array
     *
     * @param context the context
     * @param id the int array
     * @return the int array
     */
    public static int[] getIntArray(Context context, int id) {
        int[] result = null;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getIntArray();
        } catch (IOException e) {
            result = null;
        } catch (NotExistException e) {
            result = null;
        } catch (WrongTypeException e) {
            result = null;
        }
        return result;
    }

    /**
     * get the dimen value
     *
     * @param context the context
     * @param id      the id
     * @return get the float dimen value
     */
    public static float getDimen(Context context, int id) {
        float result = 0;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getFloat();
        } catch (IOException | NotExistException | WrongTypeException e) {
            result = 0;
        }
        return result;
    }
    /**
     * get string
     *
     * @param context the context
     * @param id      the string id
     * @return string of the given id
     */
    public static String getString(Context context, int id) {
        String result = "";
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            result = null;
        }
        return result;
    }

    /**
     * get boolean
     *
     * @param context the context
     * @param id      the boolean id
     * @return boolean of the given id
     */
    public static boolean getBoolean(Context context, int id) {
        boolean result = false;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getBoolean();
        } catch (IOException | NotExistException | WrongTypeException e) {
            result = false;
        }
        return result;
    }

    /**
     * get the string array
     *
     * @param context the context
     * @param id      the string array id
     * @return the string array
     */
    public static String[] getStringArray(Context context, int id) {
        String[] result = null;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getStringArray();
        } catch (IOException | NotExistException | WrongTypeException e) {
            result = null;
        }
        return result;
    }

    /**
     * get the vector drawable
     *
     * @param context the context
     * @param id      the drawable id
     * @return the vector drawable
     */
    public static VectorElement getVectorDrawable(Context context, int id) {
        if (context == null) {
            return null;
        }

        return new VectorElement(context, id);
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param id      the id
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, int id) {
        String path = getPathById(context, id);
        if (path == null || path.length() == 0) {
            return Optional.empty();
        }
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
            Optional.empty();
        }
        return Optional.empty();
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param path the path
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, String path) {
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
            Optional.empty();
        }
        return Optional.empty();
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param asset the InputStream
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, InputStream asset) {
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        ImageSource source = ImageSource.create(asset, options);
        return Optional.ofNullable(source.createPixelmap(decodingOptions));
    }

    /**
     * get the Pixel Map Element
     *
     * @param context the context
     * @param resId   the res id
     * @return the Pixel Map Element
     */
    public static PixelMapElement getPixelMapDrawable(Context context, int resId) {
        Optional<PixelMap> optional = getPixelMap(context, resId);
        return optional.map(PixelMapElement::new).orElse(null);
    }

    /**
     * get the Element
     *
     * @param color the color
     * @return the Element
     */
    public static Element buildDrawableByColor(int color) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        return drawable;
    }

    /**
     * get the Element By ColorRadius
     *
     * @param color  the color
     * @param radius the radius
     * @return the Element By ColorRadius
     */
    public static Element buildDrawableByColorRadius(int color, float radius) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.RECTANGLE);
        drawable.setRgbColor(RgbColor.fromArgbInt(color));
        drawable.setCornerRadius(radius);
        return drawable;
    }

    /**
     * get the ShapeElement
     *
     * @param thickness  the thickness
     * @param inside     the inside color
     * @param border     the border color
     * @param startAngle the start angle
     * @param sweepAngle the sweep angle
     * @return the ShapeElement
     */
    public static ShapeElement getCustomArcGradientDrawable(
            int thickness, Color inside, Color border, float startAngle, float sweepAngle) {
        ShapeElement drawable = new ShapeElement();
        drawable.setShape(ShapeElement.ARC);
        drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part
        drawable.setArc(new Arc(startAngle, sweepAngle, false));
        drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue()));
        return drawable;
    }

    /**
     * get the Element
     *
     * @param thickness the thickness
     * @param inside the inside color
     * @param border the border color
     * @param rect the rect
     * @return the Element
     */
    public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) {
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.OVAL);
        element.setRgbColor(RgbColor.fromArgbInt(inside.getValue()));
        element.setStroke(2, RgbColor.fromArgbInt(border.getValue()));
        element.setBounds(rect);
        return element;
    }

    /**
     * get the Element
     *
     * @param inside the inside color
     * @param rect the rect
     * @return the Element
     */
    public static Element getCustomRectGradientDrawable(Color inside, Rect rect) {
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.RECTANGLE);
        element.setRgbColor(RgbColor.fromArgbInt(inside.getValue()));
        element.setBounds(rect);
        return element;
    }

    /**
     * get res id by reflect
     *
     * @param resClass res class
     * @param resName  res name
     * @return res id
     */
    public static OptionalInt getResIdByReflect(Class resClass, String resName) {
        return null;
    }

    /**
     * get native city name
     *
     * @param context the context
     * @param cityId  cityId
     * @return city name from cityId
     */
    public static String getNativeCityName(Context context, String cityId) {
        return null;
    }

    /**
     * find view by id
     *
     * @param view rootView
     * @param id   res id
     * @param <T>  type
     * @return view
     */
    public static <T extends Component> T findViewById(Component view, int id) {
        if (view == null) {
            return null;
        }
        return (T) view.findComponentById(id);
    }

    /**
     * get Element from Resource
     *
     * @param resource the resource
     * @return Element
     * @throws IOException IOException
     * @throws NotExistException NotExistException
     */
    public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException {
        return new PixelMapElement(preparePixelmap(resource));
    }

    /**
     * get PixelMap from Resource
     *
     * @param resource the resource
     * @return PixelMap
     * @throws IOException IOException
     * @throws NotExistException NotExistException
     */
    public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException {
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        ImageSource imageSource = null;
        try {
            imageSource = ImageSource.create(readResource(resource), srcOpts);
        } finally {
            close(resource);
        }
        if (imageSource == null) {
            throw new FileNotFoundException();
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;

        PixelMap pixelmap = imageSource.createPixelmap(decodingOpts);
        return pixelmap;
    }

    /**
     * close Resource
     *
     * @param resource the resource
     */
    private static void close(Resource resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                return;
            }
        }
    }

    /**
     * get bytes from Resource
     *
     * @param resource the resource
     * @return bytes
     */
    private static byte[] readResource(Resource resource) {
        final int bufferSize = 1024;
        final int ioEnd = -1;

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[bufferSize];
        byte[] bytes = null;
        try {
            while (true) {
                int readLen = resource.read(buffer, 0, bufferSize);
                if (readLen == ioEnd) {
                    break;
                }
                output.write(buffer, 0, readLen);
            }
        } catch (IOException e) {
            return null;
        } finally {
            bytes = output.toByteArray();
            try {
                output.close();
            } catch (IOException e) {
                bytes = null;
            }
        }
        return bytes;
    }

    /**
     * get Element from ResourceId
     *
     * @param context the context
     * @param resId the resourceId
     * @return Element
     */
    public static Element getDrawable(Context context, int resId) {
        ResourceManager rsrc = context.getResourceManager();
        if (rsrc == null) {
            return null;
        }

        Element drawable = null;
        if (resId != 0) {
            try {
                Resource resource = rsrc.getResource(resId);
                drawable = (Element) prepareElement(resource);
            } catch (Exception e) {
                drawable = null;
            }
        }
        return drawable;
    }
}
